package com.cassio.stores.dao;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cassio.common.entity.State;
import com.cassio.stores.util.DAOConstants;
import com.cassio.stores.util.DBHelper;


public class StateDAO {
	
	public static List<State> findAll() {
		SQLiteDatabase db = DBHelper.getInstance().getReadableDatabase();
		
		String[] columns = {State.COL_ID, State.COL_CODE, State.COL_NAME};
		Cursor cursor = db.query(State.TABLE_NAME, columns, null, null, null, null, null);
		
		List<State> states = new ArrayList<State>();
		if (cursor.moveToFirst())
			do { 
				State state = new State();
				state.setId(cursor.getInt(0));
				state.setCode(cursor.getString(1));
				state.setName(cursor.getString(2));
				states.add(state);
			} while (cursor.moveToNext());

		cursor.close();
		cursor.deactivate();
		db.close();
		return states;
	}
	
	public static State find(Integer stateId) {
		SQLiteDatabase db = DBHelper.getInstance().getReadableDatabase();
		
		String[] columns = {State.COL_ID, State.COL_CODE, State.COL_NAME};
		String[] selectionArgs = {stateId.toString()};
		Cursor cursor = db.query(State.TABLE_NAME, columns, State.COL_ID + DAOConstants.EQUALS, selectionArgs , null, null, null);
		
		State state = null;
		if (cursor.moveToFirst()){
			state = new State();
			state.setId(cursor.getInt(0));
			state.setCode(cursor.getString(1));
			state.setName(cursor.getString(2));
		}
		
		cursor.close();
		cursor.deactivate();
		db.close();
		return state;
	}
}
